﻿using RndMaterialDisposalService.Attrbutes;
using RndMaterialDisposalService.Helper;
using RndMaterialDisposalService.Models.Entitys;
using RndMaterialDisposalService.Models.RequestModel;
using RndMaterialDisposalService.Models.ResponseModel;
using RndMaterialDisposalService.Models;
using RndMaterialDisposalService.Services.Interface.TemporaryDocument;
using RndMaterialDisposalService.Services.VehicleDispatchService;
using AutoMapper;
using Ganss.Excel;
using Microsoft.AspNetCore.Mvc;
using System.Text.Json;
using RndMaterialDisposalService.Services.ValidationProblemTracking;
using NPOI.SS.Formula.Functions;
using RndMaterialDisposalService.Services.Interface.OutsourcingProcessing;
using RndMaterialDisposalService.Services.Interface.SmallBatchTrial;
using System.Text.Encodings.Web;
using System.Text.Unicode;

namespace RndMaterialDisposalService.Controllers.SmallBatchTrial
{
    /// <summary>
    /// 车间加工电子流
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class WorkshopProcessingController : ControllerBase
    {
        private readonly string ProcessFullName = "SmallBatchTrial\\WorkshopProcessing";
        private readonly string SaveFormDataUrl = "/api/WorkflowData/ApplicationData";
        private readonly string ProcessFolioUrl = "/api/WorkflowData/ApplicationNumber";

        private readonly IMapper mapper;
        private readonly IConfiguration configuration;
        private readonly ILogger<WorkshopProcessingController> logger;
        private readonly IWorkshopProcessingService workshopProcessingService;
        private readonly IOutsourcingProcessingService ioutsourcingProcessingService;


        /// <summary>
        /// 
        /// </summary>
        /// <param name="_mapper"></param>
        /// <param name="_logger"></param>
        /// <param name="_workshopProcessingService"></param>
        /// <param name="_ioutsourcingProcessingService"></param>
        /// <param name="_configuration"></param>
        public WorkshopProcessingController(ILogger<WorkshopProcessingController> _logger,
            IWorkshopProcessingService _workshopProcessingService,
            IOutsourcingProcessingService _ioutsourcingProcessingService,
            IConfiguration _configuration,
            IMapper _mapper)
        {
            mapper = _mapper;
            logger = _logger;
            configuration = _configuration;
            ioutsourcingProcessingService = _ioutsourcingProcessingService;
            workshopProcessingService = _workshopProcessingService;

        }


        /// <summary>
        /// 获取表单数据
        /// </summary>
        /// <param name="procInstID"></param>
        /// <param name="mainFlowId"></param>
        /// <param name="dataKey"></param>
        /// <returns></returns>
        [HttpGet("GetFormData")]
        public async Task<IActionResult> GetFormData(string? procInstID, string? mainFlowId, string? dataKey)
        {
            var CommonServiceHost = configuration.GetSection("CommonServiceHost").Value;
            var jsonOptions = new JsonSerializerOptions()
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
                //Encoder = JavaScriptEncoder.Create(UnicodeRanges.All),
                WriteIndented = true
            };
            var result = new FormInfoResp();
            if (!string.IsNullOrEmpty(mainFlowId) && !string.IsNullOrEmpty(dataKey))
            {
                var mainFlowFormData = await ioutsourcingProcessingService.TheMainFlowFormData(mainFlowId);
                if (mainFlowFormData.determineTrackMaterialTracking.Any()) {
                    mainFlowFormData.determineTrackMaterialTracking.ForEach(p =>
                    {
                        var item = mainFlowFormData.materialTrackingDetailsList.FirstOrDefault() ?? new MaterialTrackingDetails();
                        p.engineerName = item.engineerName;
                        p.engineerID = item.engineerID;
                    });
                    mainFlowFormData.materialTrackingDetailsList = mapper.Map<List<MaterialTrackingDetails>>(mainFlowFormData.determineTrackMaterialTracking);
                }
                var formdata = mapper.Map<WorkshopProcessinFormData>((mainFlowFormData, mainFlowId, dataKey));
                result.FormData = JsonSerializer.Serialize(formdata, jsonOptions);
                var url2 = $"{CommonServiceHost}{ProcessFolioUrl}?workflowCode={ProcessFullName}";
                var appNumber = await HttpHelper.GetAsync<string>(url2);
                result.ApplicationNumber = appNumber;
                result.ViewsStatus = "Start";
                return Ok(result);
            }


            if (!string.IsNullOrEmpty(procInstID))
            {
                var url = $"{CommonServiceHost}{SaveFormDataUrl}?procInstID={procInstID}";
                result = await HttpHelper.GetAsync<FormInfoResp>(url);
                result.ViewsStatus = "Approval";
            }

            return Ok(result);

        }

        /// <summary>
        /// 保存报表数据
        /// </summary>
        /// <param name="formData"></param>
        /// <param name="mapper"></param>
        /// <returns></returns>
        [HttpPost("SaveReportData")]
        public async Task<IActionResult> SaveReportData(WorkshopProcessinFormData formData, [FromServices] IMapper mapper)
        {
            try
            {
                var model = mapper.Map<WorkshopProcessinReportDto>(formData);
                var result = await workshopProcessingService.SaveReportData(model);
                logger.LogInformation($"新增报表数据（车间加工电子流）,流程主题：{formData.FormHeader.Subject},数量：{result},时间：{DateTime.Now}");
                return Ok(result);
            }
            catch (Exception ex)
            {
                logger.LogInformation($"新增报表数据（车间加工电子流）,流程主题：{formData.FormHeader.Subject},异常原因：{ex.ToString()},时间：{DateTime.Now}");
                throw;
            }
        }

        /// <summary>
        /// 获取报表数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("GetReportData")]
        [PageList]
        public async Task<IActionResult> WorkshopProcessingReportData(WorkshopProcessinReportReq input)
        {
            var data = await workshopProcessingService.GetReportData(input);
            var result = ApiResponsePageList<WorkshopProcessinReportDto>.CreatePageListByResult(data.list, input.PageIndex, input.PageSize, data.count);
            return Ok(result);
        }

        ///// <summary>
        ///// 导出报表文件
        ///// </summary>
        ///// <param name="inputCondition"></param>
        ///// <returns></returns>
        //[HttpPost("VehicleReportExport")]
        //[PageList]
        //public async Task<IActionResult> VehicleMaintenanceReportExport(VehicleReportDataReq inputCondition)
        //{
        //    inputCondition.PageIndex = 1;
        //    inputCondition.PageSize = 65535;
        //    var data = await vehicleMaintenanceService.GetReportData(inputCondition);
        //    var fileDir = configuration.GetValue<string>("FileUploadPath");
        //    if (!System.IO.Directory.Exists($"{fileDir}\\Report"))
        //    {
        //        Directory.CreateDirectory($"{fileDir}\\Report");
        //    }
        //    var filePath = $"Report\\车间加工电子流{Guid.NewGuid().ToString("N")}.xlsx";
        //    await new ExcelMapper().SaveAsync($"{fileDir}\\{filePath}", data.list);
        //    return Ok(filePath);
        //}

    }
}
